package com.xbongbong.parent.field.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.parent.field.FieldAnalyseService;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.FilterConditionsPoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.businessrule.pojo.BusinessRuleInfoPojo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/07/07 14:25
 */
@Service("linkBusinessMultiFieldAnalyseServiceImpl")
public class LinkBusinessMultiFieldAnalyseServiceImpl implements FieldAnalyseService {

    @Override
    public List<Integer> fieldType() {
        return Arrays.asList(FieldTypeEnum.LINK_BUSINESS_MULTI.getType());
    }

    @Override
    public Object analysisData(Long formId, Integer businessType, Integer saasMark, PaasFormDataEntityExt paasFormDataEntityExt, JSONObject data, FieldAttrEntity fieldAttrEntity) throws XbbException {
       if (data.get(fieldAttrEntity.getLinkedText()) instanceof List) {
           JSONArray jsonArray = data.getJSONArray(fieldAttrEntity.getLinkedText());
           if (Objects.nonNull(jsonArray)) {
               List<String> nameList = new ArrayList<>();
               jsonArray.forEach(item->{
                   nameList.add(item.toString());
               });
               return StringUtils.join(nameList, "、");
           }
       } else {
           String value = data.getString(fieldAttrEntity.getLinkedText());
           if (Objects.nonNull(value)) {
               return value;
           }
       }
       return null;
    }

    @Override
    public Object handlerPreConditionValue(FieldAttrEntity thisField, BusinessRuleInfoPojo businessRuleInfoPojo, FilterConditionsPoJo filterCondition) throws XbbException {
        // 暂时无用
        return null;
    }
}
